package com.tensquare.article.controller;

import com.tensquare.article.pojo.Comment;
import com.tensquare.article.service.CommentService;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private RedisTemplate redisTemplate;

    //查询所有评论 GET/comment
    @GetMapping
    public Result findAll() {
        List<Comment> list = commentService.findAll();
        return new Result(true, StatusCode.OK,"查询成功",list);
    }

    //根据评论id查询评论数据 GET/comment/{commentId}
    @GetMapping("{commentId}")
    public Result findById(@PathVariable("commentId") String commentId) {
        Comment comment = commentService.findById(commentId);
        return new Result(true, StatusCode.OK,"查询成功",comment);
    }

    //新增评论数据 POST/comment
    @PostMapping
    public Result save(@RequestBody Comment comment) {
        commentService.save(comment);
        return new Result(true,StatusCode.OK,"新增成功");
    }

    //修改评论数据 PUT/comment/{commentId}
    @PutMapping("{commentId}")
    public Result updateById(@PathVariable("commentId") String commentId,
                             @RequestBody Comment comment) {
        commentService.updateById(commentId, comment);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    //删除评论
    @DeleteMapping("{commentId}")
    public Result deleteById(@PathVariable("commentId") String commentId) {
        commentService.deleteById(commentId);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    //根据文章id查询评论
    @GetMapping("/article/{articleId}")
    public Result findCommentByArticleId(@PathVariable("articleId") String articleId) {
        List<Comment> commentList = commentService.findCommentByArticleId(articleId);
        return new Result(true, StatusCode.OK,"查询成功",commentList);
    }

    //根据评论id，给评论点赞  PUT/comment/thummup/{commentId}
    @PutMapping("/thumbup/{commentId}")
    public Result thumbup(@PathVariable("commentId") String commentId) {
        //从redis中查询是否有点赞数据
        //模拟用户数据
        String userId = "123";
        //标记用户di和评论id，在redis中查询
        Object flag = redisTemplate.opsForValue().get("thumbup_" + userId + "_" + commentId);
        if (flag == null) {
            //用户没有点赞过,可以点赞
            commentService.thumbup(commentId);
            //并且保存点赞数据到redis
            redisTemplate.opsForValue().set("thumbup_" + userId + "_" + commentId,"已点赞");
            return new Result(true,StatusCode.OK,"点赞成功");
        }
        //否则已经点过赞，不能再次点赞
        return new Result(false, StatusCode.ERROR,"不能重复点赞");
    }

}
